<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            @click="addPermission(1,'0')"
          >添加权限</el-button>
          <!-- 后台需要的是字符串类型 '0',这个不固定 -->
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit ? '编辑权限点' : '新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述" required>
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="submitPremission">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, updatePermission,
  getPermissionDetail,
  delPermission } from '@/api/permission'
// 权限点转换成树形
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    // 验证输入的名称是否重复
    const validName = (rule, value, callback) => {
      // 1.先查找兄弟节点
      // 2.将兄弟节点组成一个数组
      // 3.使用includes验证
      let exitvalidName = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        exitvalidName = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      exitvalidName.map(item => item.name).includes(value) ? callback(new Error(`部门权限${value}已经存在`)) : callback()
    }

    // 验证输入的权限标识是否重复
    const validCode = (rule, value, callback) => {
      let exitvalidCode = this.originList
      if (this.isEdit) {
        exitvalidCode = this.originList.filter(item => item.id !== this.formData.id)
      }
      exitvalidCode.map(item => item.code).includes(value) ? callback(new Error(`部门权限标识${value}已经存在`)) : callback()
    }

    return {
      originList: [], // 接收精简数据
      isEdit: false, // 编辑状态
      showDialog: false, // 弹层状态
      permissionList: [], // 权限列表数据
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: validName }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      }
    }
  },
  created() {
    // 调用获取权限管理列表的数据
    this.getPermissionListFn()
  },
  methods: {
    // 删除角色权限
    async  delPermission(id) {
      this.$confirm('此操作将永久删除该角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delPermission(id)
        console.log(res)
        this.$message.success(res.message)
        this.getPermissionListFn()// 刷新列表
        this.showDialog = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 编辑权限按钮
    async editPermission(id) {
      const res = await getPermissionDetail(id)
      console.log(res)
      this.formData = res.data
      this.isEdit = true
      this.showDialog = true
    },
    // 提交权限(确定按钮)+兜底验证
    submitPremission() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        // 确定是编辑还是添加功能
        if (!this.isEdit) {
          const res = await addPermission(this.formData)
          // console.log(res)
          this.$message.success(res.message)// 成功提示
        } else { // 编辑功能
          const res = await updatePermission(this.formData)
          console.log(res)
          this.$message.success(res.message)// 成功提示
        }
        //
        // 重复代码
        this.getPermissionListFn()// 刷新数据
        this.showDialog = false// 关闭弹窗
      })
    },
    // 添加权限按钮
    addPermission(type, id) {
      this.showDialog = true// 弹框展开
      this.formData.type = type
      this.formData.pid = id
    },
    // 弹层取消按钮
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()// 清空校验
      this.showDialog = false
    },
    // 获取权限管理列表的数据
    async getPermissionListFn() {
      const res = await getPermissionList()
      // 获取精简数据
      this.originList = res.data.map(item => ({
        name: item.name,
        code: item.code,
        id: item.id,
        pid: item.pid

      }))

      console.log(res)
      this.permissionList = tranListToTreeData(res.data)
    }
  }
}
</script>

   <style lang="scss" scoped></style>

